import { Component, OnInit, ViewEncapsulation, Injector, NgZone, AfterViewInit, ViewChild } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import {
    EstimatedBatchCostDto,
    EstimatedCostServiceProxy,
    EstimatedCostDto,
    BatchServiceProxy,
    BatchDto,
    SimpleTaskDto
} from '@shared/service-proxies/service-proxies';
import { Paginator, LazyLoadEvent } from 'primeng/primeng';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import * as moment from 'moment';

@Component({
    templateUrl: './barcode.component.html',
    styleUrls: ['./barcode.component.less'],
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]
})
export class RealtimeCostBarcodeComponent extends AppComponentBase implements OnInit {
    constructor(
        injector: Injector,
        public _zone: NgZone,
        private _costService: EstimatedCostServiceProxy,
        private _batchService: BatchServiceProxy
    ) {
        super(injector);
    }
    @ViewChild('paginator') paginator: Paginator;

    categories = ['原材料', '辅材', '标准件', '工装', '外协费', '其他直接成本', '燃动', '人工', '制造费'];
    filterText = '';
    batchId = '';

    batch = new BatchDto();
    cost = new EstimatedBatchCostDto();
    typeCosts = new Array();
    detailCosts = new Array<EstimatedCostDto>();

    ngAnimateState = false;

    ngOnInit(): void {
        this.registerEvents();
        setTimeout(e => this.initDemoData(), 0);
    }

    registerEvents(): void {
        const self = this;

        function onMessageReceived(message) {
            if (message.batchId !== self.batchId) {
                return;
            }

            self.ngAnimateState = true;

            self.cost.amount += message.amount;

            let typeCost = _.find(self.typeCosts, e => e.name === message.category);

            if (typeCost) {
                typeCost.value += message.amount;
            } else {
                self.typeCosts.push({ name: message.category, value: message.amount });
            }

            self.detailCosts.unshift(message);
            if(self.detailCosts && self.detailCosts.length === 10){
                self.detailCosts.pop();
            }
            
            self.typeCosts = _.cloneDeep(self.typeCosts);
        }

        abp.event.on('app.cost.messageReceived', message => {
            self._zone.run(() => {
                onMessageReceived(message.cost);
            });
        });
    }

    getCost() {
        this.batchId = this.filterText;
        this.cost = new EstimatedBatchCostDto();
        this.initDemoData();
        if (!this.batchId) {
            return;
        }

        this._batchService.getBatchById(this.batchId).subscribe(result => {
            this.batch = result;
        });

        this._costService.getEstimatedCostByBatchId(this.batchId).subscribe(result => {
            this.cost = result;

            _.each(this.typeCosts, e => {
                let typeCost = _.find(this.cost.typeCosts, e1 => e1.category === e.name);
                if (typeCost) {
                    e.value = typeCost.amount;
                } else {
                    e.value = 0;
                }
            });

            this.typeCosts = this.typeCosts.filter(e => e.value);
        });

        this.primengTableHelper.showLoadingIndicator();

        this._costService
            .getEstimatedCosts(this.batchId, undefined, undefined, undefined, undefined, undefined, 10, 0)
            .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
            .subscribe(result => {
                this.primengTableHelper.totalRecordsCount = result.totalCount;
                this.detailCosts = result.items;
                this.primengTableHelper.hideLoadingIndicator();
            });

        this.filterText = '';
    }

    // valueFormatting(value: number): string {
    //     console.log(value);
    //     return value.toString() + '0000';
    // }

    initDemoData() {
        this.batch = new BatchDto();
        this.batch.id = '示例条码-001';
        this.batch.quantity = 1;
        this.batch.task = new SimpleTaskDto();
        this.batch.task.taskNum = '示例任务';
        this.batch.task.productId = '示例图号';
        this.batch.task.productName = '示例产品名称';

        let typeCosts = new Array();
        typeCosts.push({ name: '原材料', value: 100 });
        typeCosts.push({ name: '辅材', value: 200 });
        typeCosts.push({ name: '标准件', value: 300 });
        typeCosts.push({ name: '工装', value: 400 });
        typeCosts.push({ name: '外协费', value: 500 });
        typeCosts.push({ name: '其他直接成本', value: 600 });
        typeCosts.push({ name: '燃动', value: 700 });
        typeCosts.push({ name: '人工', value: 800 });
        typeCosts.push({ name: '制造费', value: 900 });

        this.typeCosts = typeCosts;

        this.detailCosts = new Array<EstimatedCostDto>();

        for (let index = 0; index < 9; index++) {
            let estimatedCost = new EstimatedCostDto();
            estimatedCost.batchId = '示例条码-001';
            estimatedCost.workshop = 'xx';
            estimatedCost.processSequence = 1;
            estimatedCost.processName = 'xxxx';
            estimatedCost.time = moment(new Date());
            estimatedCost.category = this.categories[index];
            estimatedCost.amount = 100 * (index + 1);
            estimatedCost.quantity = 1;
            estimatedCost.formula = 'xxx*xx+xx';
            this.detailCosts.push(estimatedCost);
        }
    }
}
